package com.cai.seckill.config.argumentResolver;

import com.cai.seckill.pojo.User;
import com.cai.seckill.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @BelongsProject secKill
 * @Package com.cai.seckill.config.argumentResolver
 * @Author Uli1024
 * @CreaterTime 2022/8/6 15:20
 */
@Component
public class UserArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private UserService userService;

    /**
     * 如果参数是User类型，才执行下面的第二个验证方法
     * 作用就是当用户
     *
     * @param methodParameter
     * @return
     */
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        Class<?> clazz = methodParameter.getParameterType();
        return clazz == User.class;
    }

    /**
     * 上面返回为true时才会执行，因为是方法参数拦截处理，这里拦截的是带有User类型参数的方法
     *
     * @param methodParameter
     * @param modelAndViewContainer
     * @param nativeWebRequest
     * @param webDataBinderFactory
     * @return
     * @throws Exception
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        //HttpServletRequest request = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        //HttpServletResponse response = nativeWebRequest.getNativeResponse(HttpServletResponse.class);
        //String ticket = CookieUtil.getCookieValue(request, "userTicket");
        //if (null == ticket) {
        //    ticket = request.getParameter("userTicket");
        //}
        //
        //if (StringUtils.isEmpty(ticket)) {
        //    //return null;
        //    throw new GlobalException(RespBeanEnum.HAVEN_LOGIN_ERROR);
        //}
        //
        //return userService.getUserByTicket(ticket, request, response);

        return UserContext.getUser();
    }
}
